package com.bfl.sa.sys.auth.mapper;

import com.bfl.sa.common.mapper.BaseMapper;
import com.bfl.sa.sys.auth.entity.Auth;
import com.google.common.collect.Sets;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Set;


public interface AuthMapper extends BaseMapper<Auth, Long> {

    Auth findByUserId(@Param("userId") Long userId);

    Auth findByGroupId(@Param("groupId") Long groupId);

    Auth findByOrganizationIdAndJobId(@Param("orgId") Long organizationId, @Param("jobId") Long jobId);

    ///////////委托给findRoleIdsImpl实现
    Set<Long> findRoleIds(@Param("userId") Long userId, Set<Long> groupIds, Set<Long> organizationIds, Set<Long> jobIds, Set<Long[]> organizationJobIds);

    default Set<Long> findRoleIdsImpl(Long userId, Set<Long> groupIds, Set<Long> organizationIds, Set<Long> jobIds, Set<Long[]> organizationJobIds) {

        Set<Long> roleIds = Sets.newHashSet();

        boolean hasGroupIds = groupIds.size() > 0;
        boolean hasOrganizationIds = organizationIds.size() > 0;
        boolean hasJobIds = jobIds.size() > 0;
        boolean hasOrganizationJobIds = organizationJobIds.size() > 0;

        StringBuilder hql = new StringBuilder("select roleIds from Auth where ");
        hql.append(" (userId=:userId) ");

        if (hasGroupIds) {
            hql.append(" or ");
            hql.append(" (groupId in (:groupIds)) ");
        }

        if (hasOrganizationIds) {
            hql.append(" or ");
            hql.append(" (( organizationId in (:organizationIds) and jobId=0 )) ");
        }

        if (hasJobIds) {
            hql.append(" or ");
            hql.append(" (( organizationId=0 and jobId in (:jobIds) )) ");
        }
        if (hasOrganizationJobIds) {
            int i = 0, l = organizationJobIds.size();
            while (i < l) {
                hql.append(" or ");
                hql.append(" ( organizationId=:organizationId_" + i + " and jobId=:jobId_" + i + " ) ");
                i++;
            }
        }

        /*Query q = em.createQuery(hql.toString());

        q.setParameter("userId", userId);

        if (hasGroupIds) {
            q.setParameter("groupIds", groupIds);
        }

        if (hasOrganizationIds) {
            q.setParameter("organizationIds", organizationIds);
        }

        if (hasJobIds) {
            q.setParameter("jobIds", jobIds);
        }
        if (hasOrganizationJobIds) {
            int i = 0;
            for (Long[] organizationJobId : organizationJobIds) {
                q.setParameter("organizationId_" + i, organizationJobId[0]);
                q.setParameter("jobId_" + i, organizationJobId[1]);
                i++;
            }
        }

        List<Set<Long>> roleIdSets = (List<Set<Long>>) q.getResultList();

        for (Set<Long> set : roleIdSets) {
            roleIds.addAll(set);
        }*/

        return roleIds;
    }

}
